#!/usr/bin/env python 
# -*- coding: utf-8 -*-
# @Time    : 2023/4/9 17:02
# @Author  : WJQ
# @Site    : 
# @File    : driver_wx.py
# @Software: PyCharm
import os
import time, json
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

import conf
from browser.driver import DriverHandler
from browser.page import PageHandler
from utils.common import CrawlerLogger, open_app


class DriverHandlerKApp(DriverHandler):
    def __init__(self, applets_name):
        super().__init__(applets_name, 86)

    @classmethod
    def create(cls, applets_name):
        self = DriverHandlerKApp(applets_name)
        return self

    def get_kuaiapp_url ( self ) -> str :
        # e.g. https://2021001123608001.hybrid.alipay-eco.com/index.html#pages/housing-fund/housing-fund?__appxPageId=3
        # 确保已经附加到应用
        pass

    def get_kuaiapp_appid ( self ) -> str :
        # e.g. 2021001123608001
        # 确保已经附加到应用
        pass

    def get_url( self ) -> (str, str):
        # 获取当前页面的 path
        try:
            url = self.get_kuaiapp_url()
            path = url.split("#")[1].split("?")[0]
            query = url.split("?")[1] if len(url.split("?")) > 1 else ""
            return path, query
        except Exception as e :
            CrawlerLogger.debug(f"Error getting driver title: {e}")
            return "pages/index/index", ""

    def get_all_pages( self, file_path ):
        with open(file_path, 'r', encoding='utf-8') as f :
            json_data = json.load(f)
        launch_params_keys = list(json_data.get('launchParams', {}).keys())
        return launch_params_keys

    def enter_mini_program(self, applets_name):
        open_app("com.bbk.appstore", "com.bbk.appstore.ui.AppStoreTabActivity", conf.CLIENT_SIDE_CONF.DEVICE_ID)
        # 等待页面加载完毕
        WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((AppiumBy.XPATH, "//*[@text='首页']"))
        )
        kill_cmd = 'adb -s {} shell am force-stop com.vivo.hybrid'.format(
            self.CAPS['deviceName'])
        os.system(kill_cmd)

        # 进入快程序
        CrawlerLogger.info(f"[*] 进入快程序...")
        PageHandler.safe_click_element(self.driver, AppiumBy.XPATH,
                                       f"//android.widget.TextView[@text = '应用']")
        WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((AppiumBy.XPATH, "//*[@text='快应用']"))
        )
        PageHandler.safe_click_element(self.driver, AppiumBy.XPATH,
                                       f"//android.widget.TextView[@text = '快应用']")
        WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((AppiumBy.XPATH, "//*[@text='最近使用']"))
        )
        PageHandler.safe_click_element(self.driver, AppiumBy.ACCESSIBILITY_ID, "搜索快应用内容和服务，点按两次即可进入搜索")
        WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((AppiumBy.XPATH, "//*[@text='历史搜索']"))
        )
        input = PageHandler.safe_find_element(self.driver, AppiumBy.CLASS_NAME, "android.widget.AutoCompleteTextView")
        input.send_keys(applets_name)
        PageHandler.safe_click_element(self.driver, AppiumBy.ACCESSIBILITY_ID, "搜索")
        time.sleep(2)
        PageHandler.safe_click_element(self.driver, AppiumBy.XPATH, f"(//android.view.View[@content-desc=\"秒开\"])[1]")

        CrawlerLogger.info(f"[*] 进入快程序成功...")

    def get_app_json( self , applets_name):
        pass

    def go_to_target_url ( self, target_title: str ) :
        pass